package com.jthinker.web.controller.common;

import com.alibaba.fastjson.JSON;
import com.jthinker.bean.vo.Condition;
import com.jthinker.bean.vo.Constant;
import com.jthinker.bean.vo.SearchFilter;
import com.jthinker.bean.enu.SortOrder;
import com.jthinker.bean.vo.UserInfo;
import com.jthinker.utils.WebUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: Gang Chen
 * Date: 2015/3/23 21:25
 */
public abstract class BaseController
{
    protected SearchFilter getSearchFilter(HttpServletRequest request)
    {
        SearchFilter filter = new SearchFilter();
        int page = WebUtils.getInt(request, "page", SearchFilter.DEFAULT_PAGE);
        int pageSize = WebUtils.getInt(request, "pageSize", SearchFilter.DEFAULT_PAGE_SIZE);
        String whereRaw = WebUtils.getString(request, "where");

        if (StringUtils.isNotBlank(whereRaw))
        {
            List<Condition> where = JSON.parseArray(whereRaw, Condition.class);
            filter.setWhere(where);
        }

        String sort = WebUtils.getString(request, "sort");
        SortOrder sortOrder = SortOrder.parse(WebUtils.getString(request, "sortOrder"));

        filter.setPage(page);
        filter.setPageSize(pageSize);

        filter.setSort(sort);
        filter.setSortOrder(sortOrder);
        return filter;
    }

    public Map<String, Object> getFailMessage(String message)
    {
        return getFailMessage(message, null);
    }

    public Map<String, Object> getFailMessage(String message, Object data)
    {
        return getMessage(true, message, data);
    }

    public Map<String, Object> getSuccessMessage(Object data)
    {
        return getSuccessMessage(null, data);
    }

    public Map<String, Object> getSuccessMessage(String message)
    {
        return getSuccessMessage(message, null);
    }

    public Map<String, Object> getSuccessMessage(String message, Object data)
    {
        return getMessage(false, message, data);
    }

    public Map<String, Object> getMessage(boolean isError, String message, Object data)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("isError", isError);
        map.put("message", message);
        map.put("data", data);
        return map;
    }

    protected boolean isEmpty(String str)
    {
        return StringUtils.isBlank(str);
    }

    public UserInfo getCurrentUser(HttpServletRequest request)
    {
        return (UserInfo) request.getSession().getAttribute(Constant.SESSION_USER);
    }

    public Long getCurrentUserId(HttpServletRequest request)
    {
        UserInfo userInfo = getCurrentUser(request);
        return userInfo != null ? userInfo.getId() : null;
    }

}
